package com.zw.cloud.influxdb.enums;

import com.alibaba.fastjson.JSON;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Objects;

/**
 * iot数据范围枚举
 */
@Getter
@Slf4j
public enum IotDataRangeEnum {
    SPEED("speed", BigDecimal.ZERO, BigDecimal.valueOf(200)),
    TOP_FEED("topFeed",BigDecimal.valueOf(-100), BigDecimal.valueOf(200)),
    LOWER_FEED("lowerFeed",BigDecimal.valueOf(-100), BigDecimal.valueOf(200)),
    BRUSH_FEED("brushFeed",BigDecimal.valueOf(-100), BigDecimal.valueOf(200)),
    FAN_SPEED("fanSpeed",BigDecimal.valueOf(0), BigDecimal.valueOf(9999)),
    EXHAUST_SPEED("exhaustSpeed",BigDecimal.valueOf(0), BigDecimal.valueOf(9999)),
    DRYING_ROOM_TEMP("dryingRoomTemp",BigDecimal.valueOf(0), BigDecimal.valueOf(9999));

    private String name;
    private BigDecimal min;
    private BigDecimal max;

    IotDataRangeEnum(String name, BigDecimal min, BigDecimal max) {
        this.name = name;
        this.min = min;
        this.max = max;
    }

    /**
     * 校验数据范围,如果超过范围设置为空
     */
    public static void checkDataOutOfRange(Object obj) {
        Class<?> aClass = obj.getClass();
        for (IotDataRangeEnum dataRangeEnum : IotDataRangeEnum.values()) {
            try {
                Field field = aClass.getDeclaredField(dataRangeEnum.getName());
                field.setAccessible(true);
                Object value = field.get(obj);
                if (Objects.isNull(value)) {
                    continue;
                }
                BigDecimal realValue = (BigDecimal) value;
                // 在数据范围内
                if (realValue.compareTo(dataRangeEnum.getMin()) >= 0 && realValue.compareTo(dataRangeEnum.getMax()) <= 0) {
                    continue;
                }
                // 不在数据范围内 设置为 null
                field.set(obj,null);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                log.warn("[IotDataRangeEnum][checkDataOutOfRange] obj is {},fieldName is {},error is ", JSON.toJSONString(obj),dataRangeEnum.getName(),e);
            }
        }

    }
}